package com.ruoyi.pm.openController;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pm.domain.ExcLog;
import com.ruoyi.pm.domain.ExcPort;
import com.ruoyi.pm.domain.ExcPortHeader;
import com.ruoyi.pm.service.IExcLogService;
import com.ruoyi.pm.service.IExcPortHeaderService;
import com.ruoyi.pm.service.IExcPortService;
import com.ruoyi.pm.util.SupplierUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/open/port")
public class OpenPortController extends BaseController {

    @Autowired
    private IExcPortService portService;

    @Autowired
    private SupplierUtil supplierUtil;

    @Autowired
    private IExcPortHeaderService excPortHeaderService;

    @Autowired
    private IExcLogService excLogService;


    @GetMapping("/sendPost/{portId}")
    public Map<String, Object> sendPost(@PathVariable("portId") Long portId) {

        ExcPort excPort = portService.selectExcPortById(portId);
        //初始化接口日志
        ExcLog excLog = new ExcLog();
        excLog.setPortId(portId);
        //组装请求报文
        Map<String, Object> inRequest = supplierUtil.assembleRequestBody(excPort);
        excLog.setToData(JSON.toJSONString(inRequest));
        excLog.setToTime(DateUtils.getNowDate());

        ExcPortHeader excPortHeader = new ExcPortHeader();
        excPortHeader.setPortId(excPort.getId());
        List<ExcPortHeader> excPortHeaders = excPortHeaderService.selectExcPortHeaderList(excPortHeader);

        Map<String, Object> supplierResponse = null;
        //请求服务方
        try {
            //现在就可以走服务方接口了得到返回
            supplierResponse = supplierUtil.sendSupplierRequest(excPort, inRequest, excPortHeaders);
            excLog.setOutTime(DateUtils.getNowDate());
            if(StringUtils.isNotEmpty(supplierResponse)) {
                excLog.setOutData(JSON.toJSONString(supplierResponse));
            }
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            excLogService.insertExcLog(excLog);
        }

        return supplierResponse;

    }
}
